﻿using Elight.Entity.Sys;
using Elight.Utility.Core;
using Elight.Utility.Network;
using Elight.Utility.ResponseModels;
using Elight.Utility.Security;
using Elight.WinForm.Common;
using Elight.WinForm.Properties;
using Elight.Utility.Other;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Elight.WinForm.Page.Sys.User
{
    public partial class AddUserForm : UIForm
    {
        public AddUserForm()
        {
            InitializeComponent();
        }
        #region 标题栏
        private void btnClose_Click(object sender, EventArgs e)
        {
            FormHelper.subForm = null;
            this.Close();
        }
        private Point mPoint;
        private void titlePanel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void titlePanel_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }

        private void btnClose_MouseEnter(object sender, EventArgs e)
        {
            btnClose.BackColor = Color.FromArgb(231, 231, 231);
        }

        private void btnClose_MouseLeave(object sender, EventArgs e)
        {
            btnClose.BackColor = Color.Transparent;

        }
        #endregion


        public UserPage ParentPage { get; set; }
        public string Id { get; set; }

        /// <summary>
        /// 画面加载，读取用户信息，显示在界面上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddUserForm_Load(object sender, EventArgs e)
        {
            if (StringHelper.IsNullOrEmpty(Id))
            {
                lblTitle.Text = "新增用户";
                txtAccount.Enabled = true;
            }
            else
            {
                lblTitle.Text = "修改用户";
                txtAccount.Enabled = false;
                txtPassword.Enabled = false;
            }
            //获取部门下拉列表的值
            bool flag = GetDepartmentCombox();
            if (!flag)
            {
                btnClose_Click(null, null);
                return;
            }
            flag = GetRoleTrans();
            if (!flag)
            {
                btnClose_Click(null, null);
                return;
            }
            if (StringHelper.IsNullOrEmpty(Id))
            {
                return;
            }
            Dictionary<string, string> parm = new Dictionary<string, string>();
            parm.Add("primaryKey", Id);
            //获得用户信息
            string url = GlobalConfig.Url + "app/system/user/getForm";
            string str = HttpUtils.DoPost(url, parm, 1000);
            if (StringHelper.IsNullOrEmpty(str))
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                btnClose_Click(null, null);
                return;
            }
            SysUser user = null;
            try
            {
                user = str.ToObject<SysUser>();
            }
            catch
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                btnClose_Click(null, null);
            }
            //给文本框赋值
            txtAccount.Text = user.Account;
            txtNickName.Text = user.NickName;
            txtName.Text = user.RealName;
            txtBirthday.Text = user.StrBirthday;
            if (user.Gender == "1")
                rdMale.Checked = true;
            else
                rdFemale.Checked = true;
            txtEmail.Text = user.Email;
            comboDept.SelectedValue = user.DepartmentId;
            txtTel.Text = user.MobilePhone;
            txtAddress.Text = user.Address;
            uiIntegerUpDown1.Value = user.SortCode.Value;
            //左边删除已存在的，右边新增这些
            foreach (string id in user.RoleId)
            {
                string name = roleIdDict[id];
                if (uiTransfer1.ItemsLeft.Contains(name))
                {
                    uiTransfer1.ItemsLeft.Remove(name);
                }
                uiTransfer1.ItemsRight.Add(name);
            }
        }

        Dictionary<string, string> roleNameDict = new Dictionary<string, string>();
        Dictionary<string, string> roleIdDict = new Dictionary<string, string>();


        /// <summary>
        /// 获得角色
        /// </summary>
        /// <returns></returns>
        private bool GetRoleTrans()
        {
            string url = GlobalConfig.Url + "app/system/role/getListTreeSelect";
            string str = HttpUtils.DoGet(url, null, 1000);
            if (StringHelper.IsNullOrEmpty(str))
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return false;
            }
            try
            {
                List<TreeSelect> list = str.ToList<TreeSelect>();
                foreach (TreeSelect select in list)
                {
                    uiTransfer1.ItemsLeft.Add(select.text);
                    roleIdDict.Add(select.id, select.text);
                    roleNameDict.Add(select.text, select.id);
                }
                return true;
            }
            catch (Exception ex)
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return false;
            }
        }

        /// <summary>
        /// 获得部门下拉列表数据
        /// </summary>
        /// <returns></returns>
        private bool GetDepartmentCombox()
        {
            string url = GlobalConfig.Url + "System/Organize/GetListTreeSelect";
            string str = HttpUtils.DoGet(url, null, 1000);
            if (StringHelper.IsNullOrEmpty(str))
            {
                this.ShowWarningDialog( "网络或服务器异常，请稍后重试", UIStyle.White);
                return false;
            }
            try
            {
                List<TreeSelect> list = str.ToList<TreeSelect>();
                List<TreeSelect> list2 = list.Where(it => it.parentId != "0").ToList();
                comboDept.ValueMember = "id";
                comboDept.DisplayMember = "text";
                comboDept.DataSource = list2;
                return true;
            }
            catch (Exception ex)
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return false;
            }
        }

        /// <summary>
        /// 确认按钮点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (StringHelper.IsNullOrEmpty(Id))
            {
                DoAdd();
            }
            else
            {
                DoUpdate();
            }
        }

        /// <summary>
        /// 执行更新操作
        /// </summary>
        private void DoUpdate()
        {
            bool flag = ChechEmpty(false);
            if (!flag)
            {
                return;
            }
            Dictionary<string, string> parms = new Dictionary<string, string>();
            parms.Add("Id", Id);
            parms.Add("Account", txtAccount.Text);
            parms.Add("NickName", txtNickName.Text);
            parms.Add("RealName", txtName.Text);
            parms.Add("StrBirthday", txtBirthday.Text);
            if (rdMale.Checked)
                parms.Add("Gender", "1");
            else
                parms.Add("Gender", "0");
            parms.Add("Email", txtEmail.Text);
            parms.Add("DepartmentId", comboDept.SelectedValue.ToString());
            parms.Add("MobilePhone", txtTel.Text);
            parms.Add("Address", txtAddress.Text);
            parms.Add("SortCode", Convert.ToString(uiIntegerUpDown1.Value));

            List<string> ids = new List<string>();
            foreach (string item in uiTransfer1.ItemsRight)
            {
                ids.Add(roleNameDict[item]);
            }
            string roleIds = StringHelper.GetStrArray(ids);
            parms.Add("roleIds", roleIds);
            parms.Add("ModifyUser", GlobalConfig.CurrentUser.Account);

            string url = GlobalConfig.Url + "app/system/user/form";
            string str = HttpUtils.DoPost(url, parms, 2000);
            if (StringHelper.IsNullOrEmpty(str))
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return;
            }
            try
            {
                AjaxResult result = str.ToObject<AjaxResult>();
                if (result.state != ResultType.Success)
                {
                    this.ShowWarningDialog(result.message, UIStyle.White);
                    return;
                }
                ParentPage.Init();
                btnClose_Click(null, null);
            }
            catch (Exception ex)
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return;
            }
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <param name="checkPassword"></param>
        /// <returns></returns>
        private bool ChechEmpty(bool checkPassword)
        {
            if (StringHelper.IsNullOrEmpty(txtAccount.Text))
            {
                this.ShowWarningDialog("账号不能为空", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(txtNickName.Text))
            {
                this.ShowWarningDialog("昵称不能为空", UIStyle.White);
                return false;
            }
            if (checkPassword)
            {
                if (StringHelper.IsNullOrEmpty(txtPassword.Text))
                {
                    this.ShowWarningDialog("初始密码不能为空", UIStyle.White);
                    return false;
                }
            }
            if (StringHelper.IsNullOrEmpty(txtName.Text))
            {
                this.ShowWarningDialog("姓名不能为空", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(txtBirthday.Text))
            {
                this.ShowWarningDialog("出生日期不能为空", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(txtEmail.Text))
            {
                this.ShowWarningDialog("邮箱不能为空", UIStyle.White);
                return false;
            }
            if (!txtEmail.Text.IsEmail())
            {
                this.ShowWarningDialog("邮箱格式不正确", UIStyle.White);
                return false;
            }

            if (StringHelper.IsNullOrEmpty(comboDept.SelectedItem.ToString()))
            {
                this.ShowWarningDialog("所属部门不能为空", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(txtTel.Text))
            {
                this.ShowWarningDialog("移动电话不能为空", UIStyle.White);
                return false;
            }
            if (!txtTel.Text.IsMobile())
            {
                this.ShowWarningDialog("移动电话格式不正确", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(txtAddress.Text))
            {
                this.ShowWarningDialog("联系地址不能为空", UIStyle.White);
                return false;
            }
            if (StringHelper.IsNullOrEmpty(uiIntegerUpDown1.Text))
            {
                this.ShowWarningDialog("排序号不能为空", UIStyle.White);
                return false;
            }
            return true;
        }


        /// <summary>
        /// 执行新增操作
        /// </summary>
        private void DoAdd()
        {
            bool flag = ChechEmpty(true);
            if (!flag)
                return;
            Dictionary<string, string> parms = new Dictionary<string, string>();
            parms.Add("Account", txtAccount.Text);
            parms.Add("NickName", txtNickName.Text);
            parms.Add("password", txtPassword.Text.MD5Encrypt());
            parms.Add("RealName", txtName.Text);
            parms.Add("StrBirthday", txtBirthday.Text);
            if (rdMale.Checked)
                parms.Add("Gender", "1");
            else
                parms.Add("Gender", "0");
            parms.Add("Email", txtEmail.Text);
            parms.Add("DepartmentId", comboDept.SelectedValue.ToString());
            parms.Add("MobilePhone", txtTel.Text);
            parms.Add("Address", txtAddress.Text);
            parms.Add("SortCode", Convert.ToString(uiIntegerUpDown1.Value));
            parms.Add("CreateUser", GlobalConfig.CurrentUser.Account);

            List<string> ids = new List<string>();
            foreach (string item in uiTransfer1.ItemsRight)
            {
                ids.Add(roleNameDict[item]);
            }
            string roleIds = StringHelper.GetStrArray(ids);
            parms.Add("roleIds", roleIds);
            string url = GlobalConfig.Url + "app/system/user/form";
            string str = HttpUtils.DoPost(url, parms, 2000);
            if (StringHelper.IsNullOrEmpty(str))
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return;
            }
            try
            {
                AjaxResult result = str.ToObject<AjaxResult>();
                if (result.state != ResultType.Success)
                {
                    this.ShowWarningDialog(result.message, UIStyle.White);
                    return;
                }
                ParentPage.Init();
                btnClose_Click(null, null);
            }
            catch (Exception ex)
            {
                this.ShowWarningDialog("网络或服务器异常，请稍后重试", UIStyle.White);
                return;
            }
        }
    }
}
